package com.luo.simple.service.impl;

import com.luo.simple.entity.Record;
import com.luo.simple.entity.RecordExample;
import com.luo.simple.entity.result.Result;
import com.luo.simple.entity.result.ResultBuilder;
import com.luo.simple.mapper.RecordMapper;
import com.luo.simple.parms.webParms.Record.RecordResult;
import com.luo.simple.service.RecordService;
import com.luo.simple.util.IdUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RecordServiceImpl implements RecordService {

    @Resource
    private RecordMapper mapper;

    @Override
    public Result insertRecord(Record record) {
        RecordResult recordResult = new RecordResult();
        if (StringUtils.isEmpty(record.getCode())) {
            if (StringUtils.isEmpty(record.getAddress())) {
                return ResultBuilder.genFailResult("钱包地址不能为空");
            }
            Record result = queryByAddress(record.getAddress());
            if (result != null) {
                recordResult.setCode(result.getCode());
                recordResult.setNumber(result.getNumber());
                return ResultBuilder.genSuccessResult(recordResult);
            }
            if (!StringUtils.isEmpty(record.getUpcode())) {
                Record r = queryByKey(record.getUpcode());
                if (r != null) {
                    r.setNumber(r.getNumber() + 1);
                    updateRecord(r);
                } else {
                    record.setUpcode(null);
                }
            }
            record.setCode(IdUtil.generateId());
            record.setNumber(0);
            mapper.insert(record);
        }
        Record result = queryByKey(record.getCode());
        if (result == null) {
            return ResultBuilder.genFailResult("当前的推广码用户不存在");
        }
        recordResult.setCode(result.getCode());
        recordResult.setNumber(result.getNumber());
        return ResultBuilder.genSuccessResult(recordResult);
    }

    @Override
    public void updateRecord(Record record) {
        mapper.updateByPrimaryKey(record);
    }

    @Override
    public Record queryByKey(String key) {
        return mapper.selectByPrimaryKey(key);
    }

    @Override
    public Record queryByAddress(String address) {
        RecordExample example = new RecordExample();
        RecordExample.Criteria criteria = example.createCriteria();
        criteria.andAddressEqualTo(address);
        List<Record> records = queryByExample(example);
        if (records != null && !records.isEmpty()) {
            return records.get(0);
        }
        return null;
    }

    @Override
    public List<Record> queryByExample(RecordExample example) {
        return mapper.selectByExample(example);
    }
}
